import { GameData } from "./GameData";

const {ccclass, property} = cc._decorator;

@ccclass
export default class MainGame extends cc.Component {

    @property(cc.Button) loadPackageBtn: cc.Button = null
    @property(cc.Button) sub1Btn: cc.Button = null
    @property(cc.Button) sub2Btn: cc.Button = null


    start() {
        this.loadPackageBtn.node.on('click', () => {
            this.startLoadPackage()
        })
        this.sub1Btn.node.on('click', () => {
            cc.director.loadScene('sub1')
        })
        this.sub2Btn.node.on('click', () => {
            cc.director.loadScene('sub2')
        })
        this.packageLoaded('all')
    }

    startLoadPackage() {
        cc.loader.downloader.loadSubpackage('package1', (err) => {
            if (err) {
                return console.error(err);
            }
            console.log('load package1 successfully.');
            this.packageLoaded('package1')
        });

        cc.loader.downloader.loadSubpackage('package2', (err) => {
            if (err) {
                return console.error(err);
            }
            console.log('load package2 successfully.');
            this.packageLoaded('package2')
        });
    }

    packageLoaded(packageName: string) {
        GameData.getIns().loadTasks[packageName] = true
        let isLoadAll = Object.keys(GameData.getIns().loadTasks).every(key => {
            return GameData.getIns().loadTasks[key]
        })        
        this.changeButtons(isLoadAll)
    }

    changeButtons(isPackageLoaded: boolean) {
        if (isPackageLoaded) {
            this.loadPackageBtn.node.active = false
            this.sub1Btn.node.active = true
            this.sub2Btn.node.active = true
        } else {
            this.loadPackageBtn.node.active = true
            this.sub1Btn.node.active = false
            this.sub2Btn.node.active = false
        }
    }

}
